<?php
defined('ABSPATH') || exit;
###############################################################################

#主题版本信息
define('_THEME_VERSION', '1.0.0'); //主题版本
define('_THEME_DEBUG', 0); //调试模式控制切勿开启
define('_THEME_TOKEN', 'token'); //主题授权TOKEN 切勿修改

###############################################################################

//调试模式显示错误日志信息
if ((defined('WP_DEBUG') && WP_DEBUG == true) || _THEME_DEBUG == true) {
    error_reporting(E_ALL);
} else {
    error_reporting(0); //关闭报错止乱码
}


/**
 * Sets up theme defaults and registers support for various WordPress features.
 */
function zb_setup() {

    load_theme_textdomain('woo', get_template_directory() . '/languages');


    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('post-formats', array('image', 'video', 'audio'));

    // add link manager // 开启友情链接功能
    add_filter('pre_option_link_manager_enabled', '__return_true');

    // This theme uses wp_nav_menu() in one location.
    register_nav_menus(
        array(
            'main-menu' => esc_html__('Site-wide top menu', 'woo'),
        )
    );

    add_theme_support(
        'html5',
        array(
            'search-form',
            'comment-form',
            'comment-list',
            'gallery',
            'caption',
            'style',
            'script',
        )
    );



    // Add theme support for selective refresh for widgets.
    add_theme_support('customize-selective-refresh-widgets');

    // 删除render_block 过滤器
    remove_filter('render_block', 'wp_render_duotone_support');
    remove_filter('render_block', 'wp_restore_group_inner_container');
    remove_filter('render_block', 'wp_render_layout_support_flag');


   //初始化安装

   require get_template_directory() . '/inc/setup-db.php';
   $ZB_SetupDb = new ZB_SetupDb();
   $ZB_SetupDb->install_db();

   

}
add_action('after_setup_theme', 'zb_setup');

/**
 * Register widget area.
 */
function zb_widgets_init() {

    register_sidebar(array(
        'name'          => esc_html__('Home', 'woo'),
        'id'            => 'home-center',
        'description'   => esc_html__('Home page module main content area', 'woo'),
        'before_widget' => '<div id="%1$s" class="home-widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '',
        'after_title'   => '',
    ));

     register_sidebar(array(
        'name'          => esc_html__('about Us', 'woo'),
        'id'            => 'about-center',
        'description'   => esc_html__('About page module main content area', 'woo'),
        'before_widget' => '<div id="%1$s" class="about-widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '',
        'after_title'   => '',
    ));
     register_sidebar(array(
        'name'          => esc_html__('Contact us', 'woo'),
        'id'            => 'contact-center',
        'description'   => esc_html__('The main content area of ​​the contact page module', 'woo'),
        'before_widget' => '<div id="%1$s" class="about-widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '',
        'after_title'   => '',
    ));

    // Get all pages with the 'page-widget.php' template
    $widget_pages = get_pages( array(
        'meta_key' => '_wp_page_template',
        'meta_value' => 'page-templates/page-widget.php'
    ) );

    // Loop through the pages and output their IDs
    foreach ( $widget_pages as $page ) {
        register_sidebar(array(
            'name'          => $page->post_title,
            'id'            => 'home-center-'.$page->ID,
            'description'   => esc_html__('Customize the module main content area', 'woo'),
            'before_widget' => '<div id="%1$s" class="home-widget %2$s">',
            'after_widget'  => '</div>',
            'before_title'  => '',
            'after_title'   => '',
        ));
    }

    unregister_widget('WP_Widget_Calendar');
    unregister_widget('WP_Widget_RSS');
    unregister_widget('WP_Widget_Meta');
    unregister_widget('WP_Widget_Search');
    unregister_widget('WP_Widget_Archives');
    unregister_widget('WP_Widget_Pages');
    unregister_widget('WP_Widget_Media_Gallery');
    unregister_widget('WP_Widget_Recent_Comments');
    unregister_widget('WP_Nav_Menu_Widget');

}
add_action('widgets_init', 'zb_widgets_init');

// Require Composer's autoloading file
if (is_file($composer = get_template_directory() . '/vendor/autoload.php')) {
    require_once $composer;
}



require_once get_template_directory() . '/inc/template-csf.php';

//主题基本优化
require_once get_template_directory() . '/inc/template-clean.php';

//主题钩子
require_once get_template_directory() . '/inc/template-filter.php';

//js CSS
require_once get_template_directory() . '/inc/template-assets.php';

//后台定制和后台安全优化
require_once get_template_directory() . '/inc/template-admin.php';


//消息推送webhook
require_once get_template_directory() . '/inc/template-mail.php';

//AJAX接口集成
require_once get_template_directory() . '/inc/template-ajax.php';

//bootstrap菜单类
require_once get_template_directory() . '/inc/template-walker.php';

//内置SEO
require_once get_template_directory() . '/inc/template-seo.php';

//主题功能标签
require_once get_template_directory() . '/inc/template-tags.php';

//主题shop
require_once get_template_directory() . '/inc/template-shop.php';

//WooCommerce样式覆盖
require_once get_template_directory() . '/inc/woocommerce-style-override.php';

//WooCommerce Ajax处理器
require_once get_template_directory() . '/inc/template-woo-ajax.php';

//WooCommerce配置应用
require_once get_template_directory() . '/inc/woocommerce-config.php';

//样式集成管理
require_once get_template_directory() . '/inc/style-integration.php';

//主题测试和验证
if (current_user_can('manage_options')) {
    require_once get_template_directory() . '/inc/theme-testing.php';
}

//语法检查系统
if (current_user_can('manage_options')) {
    require_once get_template_directory() . '/inc/syntax-checker-admin.php';
    require_once get_template_directory() . '/inc/syntax-checker-test.php';
    
    // 初始化数据库表
    register_activation_hook(__FILE__, function() {
        require_once get_template_directory() . '/inc/database-manager.php';
        $db_manager = new WBW_Database_Manager();
        $db_manager->create_tables();
    });
}

/**
 * 首页模板管理功能
 * Homepage Template Management
 */

// 获取当前选择的首页模板
function get_current_homepage_template() {
    $template = _xin('homepage_template', 'template_1');
    return $template;
}

// 根据模板类型加载对应的CSS文件
function load_homepage_template_styles() {
    if (!is_front_page() && !is_home()) {
        return;
    }
    
    $template = get_current_homepage_template();
    $template_uri = get_template_directory_uri();
    
    // 基础CSS文件（所有模板都需要）
    wp_enqueue_style('theme-plugin-css', $template_uri . '/assets/css/plugin.css', array(), _THEME_VERSION);
    wp_enqueue_style('theme-feather-css', $template_uri . '/assets/css/feather.css', array(), _THEME_VERSION);
    
    // 根据不同模板加载对应的CSS
    switch ($template) {
        case 'template_1':
            wp_enqueue_style('theme-collection-css', $template_uri . '/assets/css/collection.css', array(), _THEME_VERSION);
            wp_enqueue_style('theme-style1-css', $template_uri . '/assets/css/style1.css', array(), _THEME_VERSION);
            break;
            
        case 'template_2':
            wp_enqueue_style('theme-collection2-css', $template_uri . '/assets/css/collection2.css', array(), _THEME_VERSION);
            wp_enqueue_style('theme-style2-css', $template_uri . '/assets/css/style2.css', array(), _THEME_VERSION);
            break;
            
        case 'template_3':
            wp_enqueue_style('theme-collection3-css', $template_uri . '/assets/css/collection3.css', array(), _THEME_VERSION);
            wp_enqueue_style('theme-style3-css', $template_uri . '/assets/css/style3.css', array(), _THEME_VERSION);
            break;
    }
    
    // 公共页面样式
    wp_enqueue_style('theme-blog-css', $template_uri . '/assets/css/blog.css', array(), _THEME_VERSION);
    wp_enqueue_style('theme-other-pages-css', $template_uri . '/assets/css/other-pages.css', array(), _THEME_VERSION);
    wp_enqueue_style('theme-product-page-css', $template_uri . '/assets/css/product-page.css', array(), _THEME_VERSION);
}
add_action('wp_enqueue_scripts', 'load_homepage_template_styles', 20);

// 加载JavaScript文件
function load_homepage_template_scripts() {
    $template_uri = get_template_directory_uri();
    
    // 加载主要的JavaScript文件
    wp_enqueue_script('theme-plugin-js', $template_uri . '/assets/js/plugin.js', array('jquery'), _THEME_VERSION, true);
    wp_enqueue_script('theme-main-js', $template_uri . '/assets/js/main.js', array('jquery', 'theme-plugin-js'), _THEME_VERSION, true);
    
    // 如果启用了Bootstrap 5
    if (_xin('enable_bootstrap5', true)) {
        wp_enqueue_style('bootstrap5-css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css', array(), '5.3.0');
        wp_enqueue_script('bootstrap5-js', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js', array('jquery'), '5.3.0', true);
    }
}
add_action('wp_enqueue_scripts', 'load_homepage_template_scripts', 25);

// 禁用WooCommerce默认样式
function disable_woocommerce_default_styles() {
    if (_xin('disable_woocommerce_styles', true)) {
        // 禁用WooCommerce默认样式
        add_filter('woocommerce_enqueue_styles', '__return_empty_array');
        
        // 移除WooCommerce的默认CSS
        wp_dequeue_style('woocommerce-general');
        wp_dequeue_style('woocommerce-layout');
        wp_dequeue_style('woocommerce-smallscreen');
        wp_dequeue_style('woocommerce_frontend_styles');
        wp_dequeue_style('woocommerce_fancybox_styles');
        wp_dequeue_style('woocommerce_chosen_styles');
        wp_dequeue_style('woocommerce_prettyPhoto_css');
    }
}
add_action('wp_enqueue_scripts', 'disable_woocommerce_default_styles', 99);

// 添加自定义CSS到页面头部
function add_custom_homepage_styles() {
    $custom_css = _xin('custom_css', '');
    if (!empty($custom_css)) {
        echo '<style type="text/css" id="custom-homepage-styles">' . $custom_css . '</style>';
    }
}
add_action('wp_head', 'add_custom_homepage_styles');

// 添加自定义JavaScript到页面底部
function add_custom_homepage_scripts() {
    $custom_js = _xin('custom_js', '');
    if (!empty($custom_js)) {
        echo '<script type="text/javascript" id="custom-homepage-scripts">' . $custom_js . '</script>';
    }
}
add_action('wp_footer', 'add_custom_homepage_scripts');

// 为页面body添加模板类名
function add_homepage_template_body_class($classes) {
    if (is_front_page() || is_home()) {
        $template = get_current_homepage_template();
        $classes[] = 'homepage-' . $template;
        $classes[] = 'template-' . str_replace('template_', '', $template);
    }
    return $classes;
}
add_filter('body_class', 'add_homepage_template_body_class');

// AJAX处理模板切换（用于实时预览）
function ajax_switch_homepage_template() {
    check_ajax_referer('homepage_template_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized');
    }
    
    $template = sanitize_text_field($_POST['template']);
    $valid_templates = array('template_1', 'template_2', 'template_3');
    
    if (in_array($template, $valid_templates)) {
        $options = get_option('_new_options', array());
        $options['homepage_template'] = $template;
        update_option('_new_options', $options);
        
        wp_send_json_success(array(
            'message' => '模板已切换为: ' . $template,
            'template' => $template
        ));
    } else {
        wp_send_json_error(array(
            'message' => '无效的模板选择'
        ));
    }
}
add_action('wp_ajax_switch_homepage_template', 'ajax_switch_homepage_template');

// 为模板预览添加管理员工具栏
function add_template_admin_bar($admin_bar) {
    if (!current_user_can('manage_options') || !is_front_page()) {
        return;
    }
    
    $current_template = get_current_homepage_template();
    $template_names = array(
        'template_1' => '经典布局',
        'template_2' => '现代布局', 
        'template_3' => '时尚布局'
    );
    
    $admin_bar->add_menu(array(
        'id' => 'homepage-template-switcher',
        'title' => '首页模板: ' . $template_names[$current_template],
        'href' => admin_url('admin.php?page=wp-bootstrap-woo-settings'),
    ));
    
    foreach ($template_names as $template_key => $template_name) {
        $admin_bar->add_menu(array(
            'id' => 'switch-to-' . $template_key,
            'parent' => 'homepage-template-switcher',
            'title' => $template_name . ($current_template == $template_key ? ' (当前)' : ''),
            'href' => '#',
            'meta' => array(
                'onclick' => "switchTemplate('$template_key'); return false;"
            )
        ));
    }
}
add_action('admin_bar_menu', 'add_template_admin_bar', 999);

// 在前台添加模板切换的JavaScript
function add_template_switcher_script() {
    if (!current_user_can('manage_options') || !is_front_page()) {
        return;
    }
    ?>
    <script type="text/javascript">
    function switchTemplate(template) {
        if (confirm('确定要切换到这个模板吗？页面将会刷新。')) {
            jQuery.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: {
                    action: 'switch_homepage_template',
                    template: template,
                    nonce: '<?php echo wp_create_nonce('homepage_template_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('切换失败: ' + response.data.message);
                    }
                },
                error: function() {
                    alert('切换失败，请重试');
                }
            });
        }
    }
    </script>
    <?php
}
add_action('wp_footer', 'add_template_switcher_script');








